const md5 = require("md5-js");
const path = require("path");
// 使用动态路径，方便打包后配置
const config = require(path.join(process.cwd(), "/config.json"));

class Utils {
  /**
   * 获取配置项
   * @returns {{
   * port:number; origin:string[];
   * localhost:string;
   * tokenKey:string;
   * tokenExpire:number;
   * adminOverrideCode:string;
   * database:{username:string;password:string;database:string;host:string;port:string;dialect:string};
   * redis:{port:number;host:string;password:string;username:string;db:number};
   * email:{host:string;port:number;secure:boolean;auth:{user:string;pass:string}};
   * tencentSMS:{secretId:string;secretKey:string;appid:string;appkey:string;smsSign:string;templateId:string;indate:number;interval:number;ipMaxCount:number};
   * wxMp:{appid:string;appsecret:string;envVersion:string};
   * }}
   */
  static getConfig() {
    return config;
  }

  /**
   * 生成uuid
   * @returns {string}
   */
  static createUUID(tag = "u", len = 32) {
    let uuid = tag + Date.now().toString(32);
    for (let i = 0; i < len; i++) {
      uuid += Math.floor(Math.random() * 32).toString(32);
    }
    return uuid;
  }

  /**
   * 生成盐
   */
  static createSalt() {
    let salt = "";
    for (let i = 0; i < 6; i++) {
      salt += Math.floor(Math.random() * 32).toString(32);
    }
    return salt;
  }

  /**
   * 密码加密
   * @param {string} password
   * @param {string} salt
   */
  static hashPassword(password, salt) {
    password = Utils.trimStr(password);
    if (password.length < 6) throw new Error("密码长度不能小于6位");
    return md5(salt + md5(password));
  }

  /**
   * 校验账号格式是否为字母开头的字母和数字组合
   */
  static isAccount(account) {
    return /^[a-zA-Z][a-zA-Z0-9]{3,16}$/.test(account);
  }

  /**
   * 获取客户端基础参数
   * @param {object} req
   * @returns {{client_ip:string;client_uuid:string;token:string;user_agent:string}}
   */
  static getBaseParams(req) {
    const client_ip = req.ip.replace(/::ffff:/, "");
    const user_agent = req.headers["user-agent"];
    const client_uuid = req.headers["client_uuid"];
    const token = req.headers[Utils.getConfig().tokenKey];
    return { client_ip, client_uuid, token, user_agent };
  }

  /**
   * 根据parent_id将列表转换为树形结构
   */
  static listToTree(list, parent_id = 0) {
    const tree = [];
    list.forEach((item) => {
      if (item.parent_id === parent_id) {
        const children = Utils.listToTree(list, item.id);
        if (children.length) {
          if (item.dataValues) {
            // 如果是sequelize查询出来的数据，需要将children放到dataValues中
            item.dataValues.children = children;
          } else {
            item.children = children;
          }
        }
        tree.push(item);
      }
    });

    return tree;
  }

  /**
   * 过滤掉字符串前后的空格
   */
  static trimStr(str) {
    return str.replace(/(^\s+)|(\s+$)/g, "");
  }
}

module.exports = Utils;
